"""
嘉联机构服务实现
"""

import os
from urllib.parse import urljoin

from jlpay.services.base_service import BaseService
from jlpay.exception.exceptions import ConfigException


class JlpayOrgService(BaseService):
    """嘉联机构服务类，处理与嘉联支付系统的交互"""
    
    def __init__(self, builder):
        """
        从Builder创建JlpayOrgService实例
        
        Args:
            builder: JlpayOrgServiceBuilder实例
        """
        super().__init__(builder._config)
        
    @staticmethod
    def builder():
        """返回一个新的JlpayOrgServiceBuilder实例"""
        return JlpayOrgService.Builder()
    
    def get_api_url(self, request_class, api_path=None):
        """
        获取API URL
        
        Args:
            request_class: 请求类
            api_path: 接口路径
            
        Returns:
            完整的API URL
        """
        base_url = self.config.url
        if not base_url.endswith('/'):
            base_url += '/'
            
        if api_path:
            return urljoin(base_url, api_path.lstrip('/'))
        
        api_prefix = getattr(request_class, 'API_PREFIX', '')
        api_uri = getattr(request_class, 'API_URI', '')
        
        if not api_uri:
            raise ConfigException(f"请求类{request_class.__name__}未定义API_URI")
        
        path = api_prefix.lstrip('/') + '/' + api_uri.lstrip('/')
        return urljoin(base_url, path)
    
    class Builder:
        """嘉联机构服务构建器"""
        
        def __init__(self):
            """初始化Builder属性"""
            self._config = None
        
        def config(self, config):
            """
            设置配置
            
            Args:
                config: OrgConfig实例
                
            Returns:
                Builder实例
            """
            self._config = config
            return self
        
        def build(self):
            """
            构建JlpayOrgService实例
            
            Returns:
                JlpayOrgService实例
                
            Raises:
                ConfigException: 配置为空时抛出
            """
            if not self._config:
                raise ConfigException("config不能为空")
            
            return JlpayOrgService(self) 